# coding:utf-8
import logging
import logging.handlers
import os
import time


class MonLog(object):
    def __init__(self, logger=None):
        # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
        # 创建一个handler，用于写入日志文件
        self.logTime = time.strftime("%Y-%m-%d")
        self.logPath = os.path.abspath(os.path.join(os.path.dirname(__file__), './logs'))
        # 如果不存在这个logs文件夹，就自动创建一个
        if not os.path.exists(self.logPath):
            os.mkdir(self.logPath)
        # 日志文件的地址
        self.logName = self.logPath + '/' + self.logTime + '.amd5.cn.log'
        # fh = logging.FileHandler(self.log_name, 'a')  # python2
        # fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8')  # python3
        fh = logging.handlers.RotatingFileHandler(
            filename=self.logName,
            maxBytes=1024 * 1024 * 50,
            backupCount=5
        )
        fh.setLevel(logging.INFO)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        # 定义handler的输出格式
        formatter = logging.Formatter('[%(asctime)s] %(levelname)s [%(name)s#%(funcName)s()] : %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

        # 关闭打开的文件
        fh.close()
        ch.close()

    def log(self):
        return self.logger
